<?php

class Application_Model_UserAccount extends Application_Model_DomainObject{
    
    protected $_id;
    
    protected $_money;
    
    protected $_score; //经验值
    
    protected $_userGrade;//用户等级
    
    protected $_gradePrivilege;//特权领取情况
    
    protected $_birthday; //生日特权 0 代表没有领取 1代表领取了。一年把数据清成0.

    protected $_dateUp; //年费

    protected $_hdscore; //活动积分

    /**
     * 用户等级 -- 注册会员
     */
    const User_Login = 0;
    /**
     * 用户等级--认证会员
     */
    const User_Email = 1;
    /**
     * 用户等级--铜卡会员
     */
    const User_Copper = 2;
    /**
     * 用户等级--银卡会员
     */
    const User_Silver = 3;
    /**
     * 用户等级--金卡会员
     */
    const User_Gold = 4;
    /**
     * 用户等级--白金会员
     */
    const User_Platinum = 5;
    /**
     * 用户等级--钻石会员
     */
    const User_Diamond = 6;
    /**
     * 用户等级--双钻
     */
    const User_Double = 7;
    /**
     * 已领取奖励--认证奖励
     */
    const Grade_Email = 1;
    /**
     * 已领取奖励--铜卡奖励
     */
    const Grade_Copper = 2;
    /**
     * 已领取奖励--银卡奖励
     */
    const Grade_Silver = 3;
    /**
     * 已领取奖励--金卡奖励
     */
    const Grade_Gold = 4;
    /**
     * 已领取奖励--白金奖励
     */
    const Grade_Platinum = 5;
    /**
     * 已领取奖励--钻石奖励
     */
    const Grade_Diamond = 6;
    /**
     * 已领取奖励--双钻奖励
     */
    const Grade_Double = 7;
    /**
     * 铜卡积分
     */
    const Score_Copper = 2000;
    /**
     * 银卡积分
     */
    const Score_Silver = 5000;
    /**
     * 金卡积分
     */
    const Score_Gold = 15000;
    /**
     * 白金积分
     */
    const Score_Platinum = 40000;
    /**
     * 钻石积分
     */
    const Score_Diamond = 150000;
    /**
     * 双钻积分
     */
    const Score_Double = 1000000;
    /**
     * 积分国际运单 金额与积分比例 1：1
     */
    const ExchangeScore_Waybill = 1;
    /**
     * 积分代购 金额与积分比例 5：1 约等0.2
     */
    const ExchangeScore_Oreder = 0.2;
    /**
     * 登录 登录次数与积分比例 1:5 当天第一次登录有效
     */
    //const ExchangeScore_Login = 5;
    /**
     * 验证邮箱 50
     */
    //const ExchangeScore_AttestEmail = 50;
    /**
     * 上传头像 20
     */
    //const ExchangeScore_Pic = 20;
    /**
     * 完善个人资料 5
     */
    //const ExchangeScore_Userinfo = 5;
    
    public static function getUserGradeAll()
    {
        return array(
                   self::User_Login => "注册"
                ,  self::User_Email => "认证"
                ,  self::User_Copper => "V1"
                ,  self::User_Silver => "V2"
                ,  self::User_Gold => "V3"
                ,  self::User_Platinum => "V4"
                ,  self::User_Diamond => "V5"
                ,  self::User_Double => "V6"
        );
    }
    
    public function getUserGradeName()
    {
        $arrGrade = self::getUserGradeAll();
        return $arrGrade[$this->_userGrade];
    }

    /**
     * 获取奖励
     * 0 以前已经领取过 1 正常领取 
     */
    public function getIsReceivePrivilege()
    {
        if($this->_score >= self::Score_Copper && $this->_score < self::Score_Silver){
            
            $this->_userGrade = self::User_Copper;
            $gradePrivilege = self::Grade_Copper;
            
        } else if($this->_score >= self::Score_Silver && $this->_score < self::Score_Gold){
            
            $this->_userGrade = self::User_Silver;
            $gradePrivilege = self::Grade_Silver;
            
        } else if($this->_score >= self::Score_Gold && $this->_score < self::Score_Platinum){
            
            $this->_userGrade = self::User_Gold;
            $gradePrivilege = self::Grade_Gold;
            
        } else if($this->_score >= self::Score_Platinum && $this->_score < self::Score_Diamond){
            
            $this->_userGrade = self::User_Platinum;
            $gradePrivilege = self::Grade_Platinum;
            
        } else if($this->_score >= self::Score_Diamond && $this->_score < self::Score_Double){
            
            $this->_userGrade = self::User_Diamond;
            $gradePrivilege = self::Grade_Diamond;
            
        } else if($this->_score >= self::Score_Double){
            
            $this->_userGrade = self::User_Double;
            $gradePrivilege = self::Grade_Double;
            
        } else {
            return 0;
        }
        
        if($this->_gradePrivilege >= $gradePrivilege){ //代表该用户以前就领取过该阶段的奖励
            return 0;
        }
        
        $this->_gradePrivilege = $gradePrivilege;
        $this->getPrivilegeReward($gradePrivilege);
        $this->save();
        return 1;
    }

    /**
     * 发放奖励
     * @param type $gradePrivilege
     */
    public function getPrivilegeReward($gradePrivilege)
    {
        $dateExpired = date("Y-m-d H:i:s", time() + 90*86400);
        echo $dateExpired;exit;
        $type = Application_Model_Coupon::Type_All;
        $scope = Application_Model_Coupon::Scope_Waybill;
        $batchNo = "PrivilegeReward";
        switch ($gradePrivilege) {
            case self::Grade_Copper:
                Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 500, 50, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V1会员奖励");
                break;
            case self::Grade_Silver:
                Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 500, 50, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V2会员奖励");
                Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 500, 50, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V2会员奖励");
                break;
            case self::Grade_Gold:
                for ($index = 1; $index < 5; $index++) {
                    Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 500, 50, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V3会员奖励");
                }
                break;
            case self::Grade_Platinum:
                for ($index = 1; $index < 9; $index++) {
                    Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 500, 50, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V4会员奖励");
                }
                break;
            case self::Grade_Diamond:
                for ($index = 1; $index < 9; $index++) {
                    Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 1000, 100, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V5会员奖励");
                }
                break;
            case self::Grade_Double:
                for ($index = 1; $index < 21; $index++) {
                    Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 1000, 100, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V6会员奖励");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 添加积分
     * @param type $scoreRate 积分换率
     * @param type $money 金额
     */
    public function MoneyExchangeScore($scoreRate,$money,$comment)
    {
        $beforeScore = $this->_score;
        $this->_score = $this->_score + (int)($scoreRate * $money);
        $this->userGradeUpgrade($this->_score);
        $this->save();
        $history = new Application_Model_UserAccountHistory();
        $history->Type = Application_Model_UserAccountHistory::TYPE_ADDSCORE;
        $history->BeforeMoney = $this->_money;
        $history->AfterMoney = $this->_money;
        $history->Comment = $comment;
        $history->DateCreated = date('Y-m-d H:i:s');
        $history->RelaseId = 0;
        $history->BeforeScore = $beforeScore;
        $history->State = Application_Model_UserAccountHistory::STATE_SCORE;
        $history->AfterScore = $this->_score;
        $history->AccountId = $this->_id;
        $history->save();
    }
    
    /**
     * 完成任务添加积分
     * @param type $taskId 任务Id 
     */
    public function TaskExchangeScore($taskCode)
    {
        $taskItem = Application_Model_Task::getByTaskCode($taskCode);
        if($taskItem){
            $beforeScore = $this->_score;
            $this->_score = $this->_score + $taskItem->Score;
            $this->userGradeUpgrade($this->_score);
            $this->save();
            $taskItem->addTaskLog($this->_id);
            $history = new Application_Model_UserAccountHistory();
            $history->Type = Application_Model_UserAccountHistory::TYPE_ADDSCORE;
            $history->BeforeMoney = $this->_money;
            $history->AfterMoney = $this->_money;
            $history->Comment = $taskItem->Name;
            $history->DateCreated = date('Y-m-d H:i:s');
            $history->RelaseId = $taskItem->Id;
            $history->BeforeScore = $beforeScore;
            $history->State = Application_Model_UserAccountHistory::STATE_SCORE;
            $history->AfterScore = $this->_score;
            $history->AccountId = $this->_id;
            $history->save();
        }
    }

    /**
     * 自动升级
     * @param type $score
     */
    public function userGradeUpgrade($score)
    {
        if($score >= self::Score_Copper && $score < self::Score_Silver){
            $this->_userGrade = self::User_Copper;
        } else if($score >= self::Score_Silver && $score < self::Score_Gold){
            $this->_userGrade = self::User_Silver;
        } else if($score >= self::Score_Gold && $score < self::Score_Platinum){
            $this->_userGrade = self::User_Gold;
        } else if($score >= self::Score_Platinum && $score < self::Score_Diamond){
            $this->_userGrade = self::User_Platinum;
        } else if($score >= self::Score_Diamond && $score < self::Score_Double){
            $this->_userGrade = self::User_Diamond;
        } else if($score >= self::Score_Double){
            $this->_userGrade = self::User_Double;
        }
//        $this->save();
    }
    
    /**
     * 获得当期等级及升级所需积分
     */
    public function getNextGradeScore()
    {
        switch ($this->_userGrade) {
            case self::User_Login:
                $nextScore = self::Score_Copper;
                break;
            case self::User_Email:
                $nextScore = self::Score_Copper;
                break;
            case self::User_Copper:
                $nextScore = self::Score_Silver;
                break;
            case self::User_Silver:
                $nextScore = self::Score_Gold;
                break;
            case self::User_Gold:
                $nextScore = self::Score_Platinum;
                break;
            case self::User_Platinum:
                $nextScore = self::Score_Diamond;
                break;
            case self::User_Diamond:
                $nextScore = self::Score_Double;
                break;
            default:
                break;
        }
        return $nextScore;
    }
    
    /**
     * 获得下级等级
     */
    public function getNextGrade()
    {
        $arrGrade = self::getUserGradeAll();
        if($this->_userGrade == self::User_Login){
            $nextGrade = self::User_Copper;
        } else {
            $nextGrade = $this->_userGrade + 1;
        }
        return $arrGrade[$nextGrade];
    }
    
    /**
     * 验证邮箱
     */
    public function AttestEmail()
    {
        if($this->_userGrade<self::User_Email){
            $this->_userGrade = self::User_Email;
        }
        if($this->_gradePrivilege<self::Grade_Email){
            $this->_gradePrivilege = self::Grade_Email;
        }
        $this->TaskExchangeScore(Application_Model_Task::TASK_EMAIL);
        $this->save();
    }
    
    public function getGradeReward()
    {
        switch ($this->_userGrade) {
            case self::User_Copper:
                $html = "50元优惠券一张";
                break;
            case self::User_Silver:
                $html = "50元优惠券二张";
                break;
            case self::User_Gold:
                $html = "50元优惠券四张";
                break;
            case self::User_Platinum:
                $html = "50元优惠券八张";
                break;
            case self::User_Diamond:
                $html = "100元优惠券八张";
                break;
            case self::User_Double:
                $html = "100元优惠券二十张和ipad一台(价值未知)";
                break;
            default:
                $html = "出现未知错误，请刷新再试一下，如还不行，请联系在线客服。";
                break;
        }
        return $html;
    }

    protected static function getDb(){
        return new Application_Model_DbTable_UserAccount();
    }


    /**
     * 根据用户ID返回对应的帐户
     * @param int $userId
     * @return Application_Model_UserAccount 
     */
    public static function getByUserId($userId){
        return Application_Model_UserAccount::getDb()->getByUserId($userId);
    }
    
    /**
     * 返回当前用户的历史记录
     * @param 操作类型 $type 1、扣除余额，2、充值,3、扣除积分
     * @param type $dateStart
     * @param type $dateEnd
     * @return array 
     */
    public function getHistory($type,$dateStart,$dateEnd){
        return Application_Model_UserAccountHistory::search($this->Id,$type,$dateStart,$dateEnd);
    }
    
    public function getMoneyChange($dateStart,$dateEnd, $count, $offset){
        return Application_Model_UserAccountHistory::getMoneyChange($this->Id, $dateStart, $dateEnd, $count, $offset);
    }
    
    /**
     * 未处理代充值记录，状态为0或者5
     */
    public function getTopUpAlipay($id, $count, $offset)
    {
    	return Application_Model_topUpAlipay::getDB()->queryPage(array('userId'=>$id),'dateCreated desc',$count, $offset);    	
    }
    
    /**
     * 获取用户指定状态的代充值记录数
     * @param int $id
     * @param int $status
     */    
    public function getTopUpAlipayCount($id, $status)
    {
    	return Application_Model_topUpAlipay::getDB()->count(array('userId'=>$id,'status'=>$status));
    }
    
    /**
     * 获取用户最后一次代充值记录
     * @param int $id
     */
    public function getUserLastTopUpAlipay($id)
    {
    	return Application_Model_topUpAlipay::getDB()->queryPage(array('userId'=>$id),"dateCreated desc",1,0);
    }
    
    /**
     * 完成支付功能，从用户帐户扣除指定的金额，并记录操作记录，修改支付状态。
     * @param type $money
     * @param type $payObject 
     */
    public function pay($money,$payObject){
        try{
            $this->getDbTable()->beginTran();
            $history = new Application_Model_UserAccountHistory();
            $history->Type = Application_Model_UserAccountHistory::TYPE_DISMONEY;
            $history->BeforeMoney = $this->Money;
            $history->AfterMoney = $this->Money - $money;
            $history->Comment = $payObject->getPayCommen();
            $history->DateCreated = date('Y-m-d H:i:s');
            $history->RelaseId = $payObject->Id;
            $history->BeforeScore = $this->Score;
            $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
            $history->AfterScore = $this->Score;
            $history->AccountId = $this->Id;
            $history->save();
            
            $payObject->setPaid();
            $payObject->save();
            
            $accountItem = self::load($this->_id);
            $accountItem->Money -= $money;            
            $accountItem->save();
            
            $this->getDbTable()->commit();
        }  catch (Exception $ex){
            $this->getDbTable()->rollBack();
            throw $ex;
        }
        
    }

    
    public function recharge($paybill){
        try{
            
            $this->getDbTable()->beginTran();
            $history = new Application_Model_UserAccountHistory();
            $history->Type = Application_Model_UserAccountHistory::TYPE_RECHARGE_MONEY;
            $history->BeforeMoney = $this->Money;
            $history->AfterMoney = $this->Money + $paybill->Money;
            $history->Comment = '充值成功';
            $history->DateCreated = date('Y-m-d H:i:s');
            $history->RelaseId = $paybill->Id;
            $history->BeforeScore = $this->Score;
            $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
            $history->AfterScore = $this->Score;
            $history->AccountId = $this->Id;
            $history->save();
            
            $paybill->Status = Application_Model_PayBill::PAY_STATUS_SUCCESS;
            $paybill->save();
            
            $this->Money += $paybill->Money;            
            $this->save();
            
            $this->getDbTable()->commit();
        }catch(Exception $ex){
            $this->getDbTable()->rollBack();
            throw $ex;
        }
    }
    
    public function changeMoney($money,$type,$desc){
        $history = new Application_Model_UserAccountHistory();
        $account =  $this;
        $history->BeforeMoney = $account->Money;
        $history->AfterMoney = $account->Money + $money;
        $history->BeforeScore = $account->Score;
        $history->AfterScore = $account->Score;
        $history->DateCreated = date('Y-m-d H:i:s');
        $history->Comment = $desc;
        $history->AccountId = $this->_id;
        $history->Type = $type;
        $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
        $account->Money += $money;
        $history->save();
        $this->save();
    }
    
    public static function addAccount($userId)
    {
        $accountItem = Application_Model_UserAccount::load($userId);
        if(!$accountItem){
            $accountItem = new Application_Model_UserAccount();
            $accountItem->Id = $userId;
            $accountItem->Money = 0;
            $accountItem->Score = 0;
            $accountItem->UserGrade = self::User_Login;
            $accountItem->Birthday = 0;
            $accountItem->GradePrivilege = 0;
            $accountItem->insertId();
        }
        return $accountItem;
    }
    
    /**
     * 用户领取生日礼物
     * @return int
     */
    public function ReceiveBirthday()
    {
        if($this->_userGrade < self::User_Silver){
            return 0;
        }
        $userProfileItem = Application_Model_Profile::getByUserId($this->_id);
        if(date("m-d",  strtotime("$userProfileItem->Birthday"))!= date("m-d")){
            return 0;
        }
        $couponItem = Application_Model_Coupon::getcouponByUserIdBatchNo($this->_id, "BirthdayReward");
        foreach ($couponItem as $couponVal) {
            if(date("Y",  strtotime("$couponVal->DateCreated")) == date("Y")){
                return 0;
            }
        }
        return $this->BirthdayReward();
    }
    
    public function getBirthdayName()
    {
        switch ($this->_userGrade){
            case self::User_Silver:
                return "10元优惠券一张";
                break;
            case self::User_Gold:
                return "20元优惠券一张";
                break;
            case self::User_Platinum:
                return "50元优惠券一张";
                break;
            case self::User_Diamond:
                return "100元优惠券一张";
                break;
            case self::User_Double:
                return "100元优惠券三张";
                break;
            default:
                return 0;
                break;
        }
    }

    /**
     * 会员生日礼物
     * @return int
     */
    public function BirthdayReward()
    {
        $dateExpired = date("Y-m-d H:i:s", time() + 90*86400);
        $type = Application_Model_Coupon::Type_All;
        $scope = Application_Model_Coupon::Scope_Waybill;
        $batchNo = "BirthdayReward";
        switch ($this->_userGrade) {
            case self::User_Silver:
                Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 100, 10, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V2会员生日奖励");
                break;
            case self::User_Gold:
                Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 200, 20, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V3会员生日奖励");
                break;
            case self::User_Platinum:
                Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 500, 50, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V4会员生日奖励");
                break;
            case self::User_Diamond:
                Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 1000, 100, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V5会员生日奖励");
                break;
            case self::User_Double:
                for ($index = 1; $index < 4; $index++) {
                   Application_Model_Coupon::addCoupon($this->_id, $dateExpired, null, 1000, 100, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "V6会员生日奖励"); 
                }
                break;
            default:
                return 0;
                break;
        }
        return 1;
    }
    
    
    public function decreaseMoney($money,$comment=''){
        try{
            $this->getDbTable()->beginTran();
            $history = new Application_Model_UserAccountHistory();
            $history->Type = Application_Model_UserAccountHistory::TYPE_DISMONEY;
            $history->BeforeMoney = $this->Money;
            $history->AfterMoney = $this->Money - $money;
            $history->Comment = $comment;
            $history->DateCreated = date('Y-m-d H:i:s');
            $history->RelaseId = 0;
            $history->BeforeScore = $this->Score;
            $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
            $history->AfterScore = $this->Score;
            $history->AccountId = $this->Id;
            $history->save();
            
            $accountItem = self::load($this->_id);
            $accountItem->Money -= $money;            
            $accountItem->save();
            
            $this->getDbTable()->commit();
        }  catch (Exception $ex){
            $this->getDbTable()->rollBack();
            throw $ex;
        }
        
    }
    
}